<template>
  <el-dialog v-dialogDrag v-if="popenevTVisible" title="组织机构排序" :close-on-click-modal="false" :before-close="handleCancel" :visible.sync="popenevTVisible" width="990px">
    <el-tabs v-model="activeName" type="card">
      <!-- <el-tab-pane label="拖动排序" name="drag">
        <el-alert title="拖动进行排序,点击法院查看部门排序,点击部门查看人员排序" type="success" close-text="知道了"> </el-alert>
        <div class="tree-box">
          <el-scrollbar style="width: 330px; height: 400px">
            <el-tree class="filter-tree mt-10" :data="treeData" :props="defaultProps" :node-key="replaceFields.key" :expand-on-click-node="false" :highlight-current="true" :check-on-click-node="true" :show-checkbox="false" :check-strictly="true" draggable :allow-drop="collapse" @check-change="onSelect" :filter-node-method="filterNode" ref="tree">
              <span class="custom-tree-node" slot-scope="{ data }">
                <div>{{data.orgRank}} {{data.name}}</div>
              </span>
            </el-tree>
          </el-scrollbar>
          <el-scrollbar style="width: 330px; height: 400px">
            <el-tree class="filter-tree mt-10" :data="treeData2" :props="{ label: 'dptFullName' }" node-key="unid" default-expand-all :expand-on-click-node="false" :highlight-current="true" :check-on-click-node="true" :show-checkbox="false" :check-strictly="false" @check-change="onSelectDpt" draggable :allow-drop="dptCollapse" :filter-node-method="dptFilterNode" ref="tree2">
              <span class="custom-tree-node" slot-scope="{ data }">
                <div>{{data.pxxh}} {{data.name}}</div>
              </span>
            </el-tree>
          </el-scrollbar>
          <el-scrollbar style="width: 330px; height: 400px">
            <el-tree class="filter-tree mt-10" :data="treeData3" :props="{ label: 'name' }" node-key="unid" default-expand-all :expand-on-click-node="false" :highlight-current="true" :check-on-click-node="true" :show-checkbox="false" :check-strictly="false" draggable :allow-drop="dptCollapse" ref="tree3">
              <span class="custom-tree-node" slot-scope="{ data }">
                <div>{{data.pxxh}} {{data.name}}</div>
              </span>
            </el-tree>
          </el-scrollbar>
        </div>
      </el-tab-pane> -->
      <el-tab-pane label="编辑序号" name="edit">
        <el-alert title="点击机构查看部门排序,点击部门查看人员排序" type="success" close-text="知道了"> </el-alert>
        <div class="tree-box">
          <div style="width: 400px">
            <el-table v-loading="loading" :height="400" :data="treeData" border row-key="unid" stripe :header-cell-style="{ background: viewConfig.theadColor }">
              <el-table-column label="机构名称" prop="name" header-align="center" align="left">
                <template slot-scope="scope">
                  <span :class="{'color-blue':scope.row.unid == currentOrgId}" @click="onSelect(scope.row)">{{scope.row.name}}</span>
                </template>
              </el-table-column>
              <el-table-column width="100" label="序号" prop="pxxh" header-align="center" align="left">
                <template slot-scope="scope">
                  <el-input-number size="mini" style="width:90px" controls-position="right" :min="0" v-model="scope.row.pxxh"></el-input-number>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div style="width: 300px">
            <el-table v-loading="loading" :height="400" :data="treeData2" border row-key="unid" stripe :header-cell-style="{ background: viewConfig.theadColor }">
              <el-table-column :label="VUE_APP_THEME == 'DJ' ? '支部名称' : '部门名称'" prop="name" header-align="center" align="left">
                <template slot-scope="scope">
                  <span :class="{'color-blue':scope.row.unid == currentDptId}" @click="onSelectDpt(scope.row)">{{scope.row.name}}</span>
                </template>
              </el-table-column>
              <el-table-column width="100" label="序号" prop="pxxh" header-align="center" align="left">
                <template slot-scope="scope">
                  <el-input-number size="mini" style="width:90px" controls-position="right" :min="0" v-model="scope.row.pxxh"></el-input-number>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div style="width: 200px">
            <el-table v-loading="loading" :height="400" :data="treeData3" border row-key="unid" stripe :header-cell-style="{ background: viewConfig.theadColor }">
              <el-table-column label="人员姓名" prop="name" header-align="center" align="left"></el-table-column>
              <el-table-column label="序号" width="100" prop="pxxh" header-align="center" align="left">
                <template slot-scope="scope">
                  <el-input-number size="mini" style="width:90px" controls-position="right" :min="0" v-model="scope.row.pxxh"></el-input-number>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    <template slot="footer">
      <el-button type="primary" @click="handleCancel"> 关闭 </el-button>
      <el-button type="primary" @click="saveFyRank"> 保存机构排序 </el-button>
      <el-button type="primary" @click="saveDptRank"> {{ VUE_APP_THEME == 'DJ' ? '保存支部排序': '保存部门排序' }} </el-button>
      <el-button type="primary" @click="savePersonRank"> 保存人员排序 </el-button>
    </template>
  </el-dialog>
</template>

<script>
import { viewConfig } from "@/utils/coreConfig";
import { getZbList, getPersonList, savePersonRank, saveDptRank, saveFyRank } from '../../api/commonApi';
export default {
  data () {
    return {
      viewConfig: viewConfig,
      activeName: 'edit',
      loading: false,
      treeData: [],   // 法院列表
      treeData2: [],  // 支部列表
      treeData3: [],  // 人员列表
      multiple: false,
      replaceFields: {
        title: "label",
        key: "value"
      },
      popenevTVisible: false,
      //promise 状态
      promiseStatus: null,
      //当前法院id
      currentOrgId: "",
      //当前部门id
      currentDptId: "",
      VUE_APP_THEME: window.HC_config.VUE_APP_THEME
    }
  },
  computed: {
    defaultProps()
    {
      let tampObj = {};
      tampObj.label = this.replaceFields.title;
      return tampObj;
    }
  },
  methods: {
    // 控制只能同拖拽，不能插入
    collapse(moveNode, inNode, type)
    {
      // 不能插入
      if (type === 'inner')
      {
        return false;
      }
      // 只能同级拖拽
      if (moveNode.data.parentOrgId != inNode.data.parentOrgId)
      {
        return false;
      }

      return true;
    },
    dptCollapse(moveNode, inNode, type)
    {
      if (type === 'inner')
      {
        return false;
      }
      return true
    },
    // 过滤搜索
    filterNode(value, data)
    {
      if (!value) return true;
      return data[this.defaultProps.label].indexOf(value) !== -1;
    },
    dptFilterNode(value, data)
    {
      console.log(data);
      if (!value) return true;
      return data["name"].indexOf(vlaue) !== -1;
    },
    show(showData, treeList, replaceFields, multiple, config)
    {
      this.multiple = multiple || false;
      this.treeData = treeList || [];
      this.replaceFields = replaceFields || this.replaceFields;
      console.log(showData, treeList, replaceFields, multiple, 'show')
      if (showData && showData.constructor == Array)
      {
        this.selectedKeys = [...showData];
      }
      this.popenevTVisible = true;
      // 创建promise
      return new Promise((resolve, reject) => {
        this.promiseStatus = {
          resolve,
          reject
        }
      })
    },
    // 组织选择
    onSelect(data, check, tree)
    {
      this.currentOrgId = data[this.replaceFields.key]
      getZbList({
        unid: data[this.replaceFields.key]
      }).then(res => {
        this.treeData2 = res.result || []
        this.treeData2.forEach((pre_item, index) => {
          pre_item.xh = index + 1
        })
        this.treeData2.sort((a,b) => {
          return (a.pxxh - b.pxxh);
        })
      })
    },
    // 部门选择
    onSelectDpt(data, check, tree)
    {
      this.currentDptId = data.unid;
      getPersonList({
        unid: data.unid
      }).then(res => {
        this.treeData3 = res.result || []
        this.treeData3.forEach((pre_item, index) => {
          pre_item.xh = index + 1
        })
        this.treeData3.sort((a, b) => {
          return (a.pxxh - b.pxxh)
        })
      })
    },
    handleCancel()
    {
      this.popenevTVisible = false;
      // 清空勾选项
      this.promiseStatus.reject({
        msg: "取消"
      })
      this.selectedKeys = []
    },
    // 保存法院排序
    saveFyRank()
    {
      // 根据所在数组索引，生成排序
      let tampArr = [];
      this.upDataRank(this.treeData, "pxxh", tampArr)
      console.log(tampArr)
      saveFyRank(tampArr).then(res => {
        console.log(res, '保存法院')
        this.treeData.sort((a, b) => {
          return (a.pxxh - b.pxxh)
        })
        this.$message.success(res.message || "操作成功")
      })
    },
    // 保存部门排序
    saveDptRank()
    {
      let tampArr = []
      this.upDataRank(this.treeData2, "pxxh", tampArr)
      console.log(tampArr, 'tampArr')
      saveDptRank(tampArr).then(res => {
        console.log(res, '保存支部')
        // 刷新
        this.onSelect({unid: this.currentOrgId})
        this.$message.success(res.message || "操作成功")
      })
    },
    // 保存人员排序
    savePersonRank()
    {
      let tampArr = [];
      this.upDataRank(this.treeData3, "pxxh", tampArr)
      console.log(tampArr, 'tampArr')
      savePersonRank(tampArr).then(res => {
        console.log(res, '保存')
        // 刷新
        this.onSelectDpt({unid: this.currentDptId})
        this.$message.success(res.message || "操作成功")
      })
    },
    // 生成排序
    upDataRank(treeData, rankKey, tampArr, parentOrg)
    {
      treeData.forEach((element, index) => {
        if (this.activeName == 'drag')
        {
          // 拖拽模式下更新索引生成排序号
          if (parentOrg)
          {
            console.log(parentOrg)
            if (parentOrg[rankKey])
            {
              element[rankKey] = Number((parentOrg[rankKey] + "") + ((index + 1)));
            }
            else
            {
              element[rankKey] = (index + 1)
            }
          }
          else
          {
            element[rankKey] = (index + 1)
          }
        }
        if (element.children && element.children.length > 0)
        {
          this.upDataRank(element.children, rankKey, tampArr, element)
        }
        let etyBase = JSON.parse(JSON.stringify(element))
        etyBase.children = []
        tampArr.push(etyBase);
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.tree-box {
  display: flex;
  justify-content: space-between;
}
.tree-box ::v-deep td {
  cursor: pointer !important;
}

::v-deep .el-scrollbar__wrap {
  overflow-x: hidden;
}

.color-blue {
  color: #1890ff;
}
</style>